using System;
using System.IO;
using BaseUtil;

public class XMLBufFileReader
{
    /// <summary>
    /// Read byte file of source xml file.
    /// </summary>
    public static object ReadXmlBuf(string fileName)
    {
#if UNITY_PROFILER_MONO
        // MonoProfiler.BeginSample("begin: " + fileName, MonoProfiler.MonoProType.config);
#endif
        byte[] fileContext = null;

        try
        {
            if (!XMLObjectRegister.ContainsInFileList(fileName)
                && !XMLObjectRegister.ContainsInFolderList(fileName))
            {
                return null;
            }

            var fileCDNPath = "";
            if (fileName.EndsWith(".xml"))
            {
                fileCDNPath = Path.Combine(Consts.LOGIC_TARGET_CONFIG_DIR, fileName + ".bytes");
            }
            else
            {
                fileCDNPath = Path.Combine(Consts.LOGIC_TARGET_CONFIG_DIR, fileName + ".xml.bytes");
            }

            // Read from SD card First. If File Exist In SD card, will not read from streaming resource dir.
            if (FileUtil.CheckFileExist(fileCDNPath, EnumFileType.PERSISTENT))
            {
                fileContext = FileUtil.ReadFileToBytes(fileCDNPath, EnumFileType.PERSISTENT);
            }
            else
            {
                fileContext = FileUtil.ReadFileToBytes(fileCDNPath, EnumFileType.STREAMING_ASSETS);
            }
        }
        catch (Exception ex)
        {
            LogWrapper.LogError("[XMLBufFileReader][ReadXmlBuf]", fileName, ", \n exception:", ex.StackTrace);
            return null;
        }

        try
        {
            var buf = new NetBuffer(fileContext);
            var ins = new NetInStream(buf);
            var objname = "";
            ins.Read(ref objname);
            var t = XMLObjectRegister.FindXMLObject(objname);
            if (t == null)
            {
                LogWrapper.LogError("[XMLBufFileReader][ReadXmlBuf]", fileName, "\n", objname, " not find");
                return null;
            }

            var xmlObj = Activator.CreateInstance(t);
            var xmlData = xmlObj as IXMLData;
            if (xmlData != null)
            {
                xmlData.ReadFromBuf(ins);
            }
            else
            {
                LogWrapper.LogError("[XMLBufFileReader][ReadXmlBuf]", t.ToString(), " is not xmlData");
                return null;
            }

#if UNITY_PROFILER_MONO
            // MonoProfiler.BeginSample("end " + fileName, MonoProfiler.MonoProType.config);
#endif
            return xmlObj;
        }
        catch (Exception e)
        {
            LogWrapper.LogError("[XMLBufFileReader][ReadXmlBuf] Read NetInStream error! fileName : ", fileName,
                ", exception : ", e.Message);
            return null;
        }
    }
}